'use strict';

const BaseService = require('./base');

class UserService extends BaseService {

    /**
     * 查找一个用户
     * @param {*} idType 
     * @param {*} uId 
     */
    async findOneUser(idType, uId) {
        return new Promise(async (reslove, reject) => {
            await this.ctx.model.User.findOne({
                [`${idType}`]: uId
            }, (err, res) => {
                if (err) {
                    reject(err);
                } else {
                    reslove(res);
                }
            });
        });
    }

    /**
     * 添加一个用户
     * @param {*} userInfo 
     */
    async addUser(userInfo) {
        return new Promise(async (reslove, reject) => {
            let model = new this.ctx.model.User(userInfo);
            await model.save((err, res) => {
                if (err) {
                    reject(err);
                } else {
                    reslove(res);
                }
            });
        });
    }

    /**
     * 查找所有用户
     */
    async findUser() {
        return new Promise(async (reslove, reject) => {
            await this.ctx.model.User.find((err, res) => {
                if (err) {
                    reject(err);
                } else {
                    reslove(res);
                }
            });
        })
    }

    /**
     * 更新用户
     * @param {*} idType 
     * @param {*} uId 
     * @param {*} newDoc 
     */
    async updateOneUser(idType, uId, newDoc) {
        return new Promise(async (reslove, reject) => {
            await this.ctx.model.User.updateOne({
                [`${idType}`]: uId
            }, newDoc, null, (err, res) => {
                if (err) {
                    reject(err);
                } else {
                    reslove(res);
                }
            });
        });
    }

}

module.exports = UserService;
